package com.changgou.gateway.filter;

import com.changgou.gateway.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ProjectName: changgou_parent
 * @Package: com.changgou.gateway.filter
 * @ClassName: AuthorizeFilter
 * @Author: 孙明田
 * @Description: 过滤器
 * @Date: 2020/6/13 16:23
 * @Version: 1.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3.判断是否登陆请求,是则放行
        if (request.getURI().getPath().contains("/admin/login")) {
            return chain.filter(exchange);
        }

        //4.获取所有请求头信息
        HttpHeaders headers = request.getHeaders();

        //5.获取jwt令牌信息
        String jwtToken = headers.getFirst("token");

        //6.判断token是否存在,不存在则发送错误提示信息
        if (StringUtils.isEmpty(jwtToken)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        try {
            //6.1存在，判断token是否合法，不合法则发送错误提示信息
            JwtUtil.parseJWT(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.2合法，则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
